import axios from 'axios'
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import localforage from 'localforage'

export function pointsCloudDetails(qaResultId) {
  const data = {
    qaResultId,
  }
  return request({
    url: '/mark/onlineCheck/pointsCloudDetails',
    method: 'get',
    params: data,
  })
}

export function getMarkAnnotations(taskId) {
  const data = {
    taskId,
  }
  return request({
    url: '/mark/onlineCheck/getMarkAnnotations',
    method: 'get',
    params: data,
  })
}

export function imageFile(qaResultId, imgIndex) {
  const data = {
    qaResultId,
    imgIndex,
  }
  return request({
    url: '/mark/onlineCheck/imageFile',
    method: 'post',
    params: data,
  })
}

export function pcdBlob(fileName) {
  let url = process.env.VUE_APP_BASE_API + '/mark/onlineCheck/pcdBlob?fileName=' + encodeURI(fileName)
  return axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { Authorization: 'Bearer ' + getToken() },
  })
}

export function pcdBlobWithFlag(fileName, pcdFlag) {
  let url =
    process.env.VUE_APP_BASE_API +
    '/mark/onlineCheck/pcdBlobWithFlag?fileName=' +
    encodeURI(fileName) +
    '&pcdFlag=' +
    encodeURI(pcdFlag)
  return axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { Authorization: 'Bearer ' + getToken() },
  })
}

// 获取图片文件,优先从缓存获取
export async function getImageWithCache(mQaResultId, count) {
  const images = []
  for (let i = 0; i < count; i++) {
    const imageKey = mQaResultId + ':img' + i
    const cacheKey = 'MA:' + imageKey
    let frameData
    try {
      frameData = await localforage.getItem(cacheKey)
      if (frameData == null) throw new Error('no cache')
      console.log('Load frame/annotation from cache')
    } catch (error) {
      const response = await imageFile(mQaResultId, i)
      const { imageSrc, annotation } = response
      const image = imageSrc.startsWith('http') ? imageSrc : 'data:image/gif;base64,' + imageSrc
      frameData = { blob: image, filename: annotation.fileName, mQaResultId }
      await localforage.setItem(cacheKey, frameData)
      console.log('Load frame/annotation from server', imageKey)
    }
    images.push(frameData)
  }
  return images
}
